//
//  CountDownView.swift
//  memo
//
//  Created by DaleGuo on 2023/10/18.
//

import ActivityKit
import SwiftUI

struct CountDownView: View {
    
    @State private var acticity : Activity<CountDonwAttributes>? = nil
    
    var body: some View {
        VStack(spacing: 15) {
            Button("Start Activity") {
                startActivity()
            }

            Button("Stop Activity") {
                stopActivity()
            }
        }
        .buttonStyle(.borderedProminent)
        .controlSize(.large)
    }

    func startActivity() {
        let attributes = CountDonwAttributes(timerName: "Memo Timer")
        let state = CountDonwAttributes.TimerStatus(endTime: Date().addingTimeInterval(60 * 5))
        
        let content = ActivityContent(state: state, staleDate: Calendar.current.date(byAdding: .hour, value: 1, to: Date()))
        
//        try? Activity<CountDonwAttributes>.request(attributes: attributes, contentState: state, pushType: nil)
        
        acticity = try? Activity<CountDonwAttributes>.request(attributes: attributes, content: content, pushType: nil)
    }

    func stopActivity() {
        let state = CountDonwAttributes.TimerStatus(endTime: .now)
        let content = ActivityContent(state: state, staleDate: .now)
        
        Task {
            await acticity?.end(content, dismissalPolicy: .immediate)
        }
        
    }
    
    func updateActivity() {
        let state = CountDonwAttributes.TimerStatus(endTime: Date().addingTimeInterval(60*10))
        let content = ActivityContent(state: state, staleDate: .now)
        
        Task {
            await acticity?.update(content)
        }
    }
    
}

#Preview {
    CountDownView()
}
